package com.battery.web.controller.system.battery;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.battery.common.entity.BatteryEntity;
import com.battery.common.utils.BatteryJSONResult;
import com.battery.common.utils.Constants;
import com.battery.common.utils.ExcelUtils;
import com.battery.common.utils.excel.DeviceExcel;
import com.battery.common.utils.http.HttpClientJSONUtil;
import com.battery.common.utils.security.Md5Utils;
import com.battery.system.domain.BO.DeviceBO;
import com.battery.system.domain.Prorely;
import com.battery.system.domain.VO.DevAnalysisVO;
import com.battery.system.domain.VO.DeviceVO;
import com.battery.system.service.battery.IProrelyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.battery.common.annotation.Log;
import com.battery.common.enums.BusinessType;
import com.battery.system.domain.Device;
import com.battery.system.service.battery.IDeviceService;
import com.battery.common.core.controller.BaseController;
import com.battery.common.core.domain.AjaxResult;
import com.battery.common.utils.poi.ExcelUtil;
import com.battery.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备Controller
 *
 * @author battery
 * @date 2021-01-23
 */
@Controller
@RequestMapping("/system/device")
public class DeviceController extends BaseController {


    private String prefix = "system/device";

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IProrelyService prorelyService;


    /**
     * 跳转到仓库列表页面
     *
     * @return
     */
    @RequiresPermissions("system:device:warehouseView")
    @GetMapping("/warehouse")
    public String warehouse() {
        return prefix + "/warehouse";
    }


    /**
     * 查询设备列表 (仓库)
     */
    @RequiresPermissions("system:device:warehouseList")
    @PostMapping("/warehouseList")
    @ResponseBody
    public TableDataInfo warehouseList(DeviceBO deviceBO) {
        startPage();
        List<DeviceVO> list = deviceService.selectWarehouseList(deviceBO);
        return getDataTable(list);
    }


    /**
     * 展示设备列表数据
     *
     * @return
     */
    @RequiresPermissions("system:device:view")
    @GetMapping()
    public String device() {
        return prefix + "/device";
    }

    /**
     * 查询设备列表
     */
    @RequiresPermissions("system:device:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DeviceBO deviceBO) {
        startPage();
//        List<Device> list = deviceService.selectDeviceList(device);
        List<DeviceVO> list = deviceService.selectDeviceVOList(deviceBO);
        return getDataTable(list);
    }


    /**
     * 设备营业额
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/devIncomes/{id}")
    public String devIncomes(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("deviceId", id);
        return prefix + "/devIncomes";
    }


    @RequiresPermissions(value = {"system:partner:devIncome", "system:store:devIncome", "system:device:devIncome"}, logical = Logical.OR)
    @PostMapping("/listDevIncome")
    @ResponseBody
    public TableDataInfo listDevIncome(DeviceBO deviceBO) {
        startPage();
        List<DeviceVO> list = deviceService.listDevIncome(deviceBO);
        return getDataTable(list);
    }

    /**
     * 导出设备列表
     */
    @RequiresPermissions("system:device:export")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Device device) {
        List<Device> list = deviceService.selectDeviceList(device);
        ExcelUtil<Device> util = new ExcelUtil<Device>(Device.class);
        return util.exportExcel(list, "device");
    }


    /**
     * 新增设备
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存设备
     */
    @RequiresPermissions("system:device:add")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Device device) {
        return toAjax(deviceService.insertDevice(device));
    }

    /**
     * 修改设备
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        Device device = deviceService.selectDeviceById(id);
        mmap.put("device", device);
        return prefix + "/edit";
    }


    /**
     * 修改保存设备
     */
    @RequiresPermissions("system:device:edit")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Device device) {
        return toAjax(deviceService.updateByPrimaryKeySelective(device));
    }

    /**
     * 删除设备
     */
    @RequiresPermissions("system:device:remove")
    @Log(title = "设备", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        if (StringUtils.isBlank(ids)) {
            return error("ids为空");
        }
        if (ids.contains(",")) {
            return error("暂时不支持批量操作");
        }
        return toAjax(deviceService.deleteLogicDeviceById(ids));
    }


    /**
     * 导入TCP设备SN信息
     *
     * @param file
     * @return
     */
    @RequiresPermissions("system:device:readExcel")
    @Log(title = "设备", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file) {
        String result = "";
        List<DeviceExcel> list = ExcelUtils.readExcel("", DeviceExcel.class, file);
        if (list != null && list.size() > 0) {
            result = deviceService.importExcel(list);
        }
        return success(result);
    }

    /**
     * 划分设备
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/allotDevOne/{id}")
    public String allotDevOne(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("id", id);
        return prefix + "/allotDevOne";
    }


    /**
     * 批量划分设备
     *
     * @param ids
     * @param mmap
     * @return
     */
    @GetMapping("/allotDevAll/{id}")
    public String allotDevAll(@PathVariable("id") String ids, ModelMap mmap) {
        mmap.put("ids", ids);
//        System.out.println(ids);
        return prefix + "/allotDevAll";
    }


    /**
     * 批量选择活动
     *
     * @param ids
     * @param mmap
     * @return
     */
    @GetMapping("/devChoseEvents/{id}")
    public String devChoseEvents(@PathVariable("id") String ids, ModelMap mmap) {
        mmap.put("ids", ids);
        return prefix + "/devChoseEvents";
    }


    @RequiresPermissions("system:device:allot")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PostMapping("/devChoseEvents")
    @ResponseBody
    public AjaxResult devChoseEvents(Device device) {
        if (StringUtils.isBlank(device.getId())) {
            return error("设备主键ID为空");
        }

        if (StringUtils.isBlank(device.getEventId())) {
            return error("请选择活动");
        }

        return toAjax(deviceService.devChoseEvents(device));
    }

    /**
     * 划分设备
     *
     * @param device
     * @return
     */
    @RequiresPermissions("system:device:allot")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PostMapping("/allotDevOne")
    @ResponseBody
    public AjaxResult allotDevOne(Device device) {

        if (StringUtils.isBlank(device.getId())) {
            return error("设备主键ID为空");
        }

        if (StringUtils.isBlank(device.getPartnerId())) {
            return error("请选择合作商");
        }

        return toAjax(deviceService.allotDevOne(device));
    }


    /**
     * 批量划分设备
     *
     * @param device
     * @return
     */
    @RequiresPermissions("system:device:allot")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PostMapping("/allotDevAll")
    @ResponseBody
    public AjaxResult allotDevAll(Device device) {

        if (StringUtils.isBlank(device.getId())) {
            return error("设备主键ID为空");
        }

        if (StringUtils.isBlank(device.getPartnerId())) {
            return error("请选择合作商");
        }

        return toAjax(deviceService.allotDevAll(device));
    }

    /**
     * 查看设备详情信息
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/queryStock/{id}")
    public String showStockDetail(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("deviceId", id);
        return prefix + "/queryStock";
    }

    /**
     * 列出设备库存信息
     *
     * @param id
     * @return
     */
    @PostMapping("/listStock")
    @ResponseBody
    public TableDataInfo listStock(String id) {
        startPage();
        List<BatteryEntity> list = deviceService.getBatteryStockDetail(id);
        return getDataTable(list);
    }


    /**
     * \
     * 设备返回仓库操作
     *
     * @param id
     * @return
     */
    @Log(title = "设备返回仓局", businessType = BusinessType.OTHER)
    @PostMapping("/returnWarehouse")
    @ResponseBody
    public AjaxResult returnWarehouse(String id) {
        if (StringUtils.isBlank(id)) {
            return error("主键ID不能为空");
        }

        return toAjax(deviceService.returnWarehouse(id));
    }

    /**
     * 检测设备是否在线
     *
     * @param id
     * @return
     */
    @Log(title = "检测设备是否在线", businessType = BusinessType.OTHER)
    @PostMapping("/checkOnline")
    @ResponseBody
    public AjaxResult checkOnline(String id) {
        Device device = deviceService.selectDeviceById(id);
        String sn = device.getSn();
        Prorely prorely = prorelyService.selectBySn(device.getSn());
        if (prorely == null) {
            return error("设备【" + sn + "】租借依据不存在");
        }
        String service = prorely.getService();
        int port = prorely.getPort() + 100;
        String url = "http://" + service + ":" + port + "/dev/boxStatus";
        String salt = Constants.ws_borrow_slat;
        String before = sn + salt;
        String sign = Md5Utils.hash(before);
        JSONObject requestJSON = new JSONObject();
        requestJSON.put("sn", sn);
        requestJSON.put("sign", sign);
        int status = 0;
        try {
            String responseStrPopup = HttpClientJSONUtil.postJSONUTF8(url, JSON.toJSONString(requestJSON));
            BatteryJSONResult result = JSON.parseObject(responseStrPopup, BatteryJSONResult.class);
            if (result == null) {
                status = 1;
            }
            if (result.getCode() != 200) {
                status = 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = 1;
        }
        Device updateDev = new Device();
        updateDev.setId(device.getId());
        updateDev.setDevStatus(status);
        deviceService.updateByPrimaryKeySelective(updateDev);
        if (status == 1) {
            return success("设备不在线");
        } else {
            return success("设备在线");
        }
    }


    /**
     * 弹出电池
     *
     * @param slot
     * @param deviceId
     * @return
     */
    @RequiresPermissions("system:device:popupBattery")
    @Log(title = "弹出电池", businessType = BusinessType.OTHER)
    @PostMapping("/popupBattery")
    @ResponseBody
    public AjaxResult popupBattery(Integer slot, String deviceId) {
        // TODO
        Device device = deviceService.selectDeviceById(deviceId);
        String sn = device.getSn();
        Prorely prorely = prorelyService.selectBySn(device.getSn());

        if (prorely == null) {
            return error("设备【" + sn + "】租借依据不存在");
        }
        String service = prorely.getService();
        int port = prorely.getPort() + 100;
        String url = "http://" + service + ":" + port + "/dev/popup";
        String salt = Constants.ws_borrow_slat;
        int charge = 1;
        JSONObject popupSendObj = new JSONObject();
        popupSendObj.put("sn", sn);
        popupSendObj.put("slot", slot);
        popupSendObj.put("charge", charge);
        String beforePopup = sn + slot + charge + salt;
        popupSendObj.put("sign", Md5Utils.hash(beforePopup));
        try {
            String responseStrPopup = HttpClientJSONUtil.postJSONUTF8(url, JSON.toJSONString(popupSendObj));
            BatteryJSONResult result = JSON.parseObject(responseStrPopup, BatteryJSONResult.class);
            if (result == null) {
                return error("设备不在线");
            }
            if (result.getCode().intValue() != 200) {
                return error("设备不在线");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("设备不在线");
        }
        return success("弹出成功");
    }


    /**
     * 跳转到合作商设备列表页面
     */
    @GetMapping("/partnerDev/{id}/{type}")
    public String partnerDev(@PathVariable("id") String id, @PathVariable("type") Integer type, ModelMap mmap) {
        mmap.put("partnerId", id);
        mmap.put("deviceStatus", type);
        return prefix + "/partnerDev";
    }


    /**
     * 总设备数统计分析
     *
     * @param mmap
     * @return
     */
    @GetMapping("/devAnalysis")
    public String devAnalysis(ModelMap mmap) {
        DevAnalysisVO devAnalysisVO = deviceService.selectDevAnalysis();
        mmap.put("deviceVO", devAnalysisVO);
        return prefix + "/devAnalysis";
    }


}
